package com.dc.common.util;

import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;

/**
 * 加密工具类
 *
 * @author Enzo
 * @date 2020-5-6
 */
public class EncryptUtil {


    /**
     * md5加密,32位小写加密
     *
     * @param context
     * @return java.lang.String
     * @author Enzo
     * @date 2020-5-9
     **/
    public static String encryptByMd5(String context) {
        String res = "";
        try {
            MessageDigest md = MessageDigest.getInstance("MD5");
            //update处理
            md.update(context.getBytes());
            //调用该方法完成计算
            byte[] encryContext = md.digest();
            int i;
            StringBuffer buf = new StringBuffer("");
            for (int offset = 0; offset < encryContext.length; offset++) {
                //做相应的转化（十六进制）
                i = encryContext[offset];
                if (i < 0) {
                    i += 256;
                }
                if (i < 16) {
                    buf.append("0");
                }
                buf.append(Integer.toHexString(i));
            }
            res = buf.toString();
//            System.out.println("32result: " + buf.toString());// 32位的加密
//            System.out.println("16result: " + buf.toString().substring(8, 24));// 16位的加密
        } catch (NoSuchAlgorithmException e) {
            new RuntimeException("MD5加密异常", e);
        }
        return res;
    }

}
